package com.dlc.beijingrfid.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.activity.MainActivity;
import com.dlc.beijingrfid.base.BaseFragment;
import com.dlc.commonlibrary.adapter.AdapterScanner;
import com.dlc.commonlibrary.ble.BleConstant;
import com.dlc.commonlibrary.ble.ClassScanner;
import com.dlc.commonlibrary.ble.RRUA100API;
import com.dlc.commonlibrary.utils.ToastUtil;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;

//import com.google.android.gms.location.LocationClient;

public class FragmentScannerListFragment extends BaseFragment implements OnClickListener {
	public static final String ARG_TAP_NUMBER = "tap_number";
	private final String TAG = "connected_check";
	private View rootView;
	private BluetoothAdapter mBTadapter;
	private Set<BluetoothDevice> mBTpaired;
	private RRUA100API mA100 = null;
	private ListView DeviceListView;
	private ArrayList<ClassScanner> DeviceList;
	private AdapterScanner ListAdapter;
	String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
	public String mLast_addr = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Retain this fragment across configuration changes.
		setRetainInstance(true);
		
		// Put objects which you do not want to be created again.
		// ie. run once.
		
		// Register for broadcasts when a device is discovered
		IntentFilter action_found = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        getActivity().registerReceiver(mReceiver, action_found);

        IntentFilter action_bond = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        getActivity().registerReceiver(mReceiver, action_bond);

        IntentFilter action_disconnected = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        getActivity().registerReceiver(mReceiver, action_disconnected);

        IntentFilter action_discover_end = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        getActivity().registerReceiver(mReceiver, action_discover_end);

        IntentFilter action_pairing_request = new IntentFilter(ACTION_PAIRING_REQUEST);
        getActivity().registerReceiver(mReceiver, action_pairing_request);
	}

	@Override
	public void onCreateView() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_scanner_list, container, false);
		DeviceListView = (ListView) rootView.findViewById(R.id.lv_BT_paired);
		DeviceListView.setAdapter(ListAdapter);
		DeviceListView.setOnItemLongClickListener(mDeviceLongClickListener);
		DeviceListView.setOnItemClickListener(mDeviceClickListener);
		
		Button btn_search = (Button) rootView.findViewById(R.id.button_BT_search);
		btn_search.setOnClickListener(this);
        PairedListUpdate("");
      //  discovery_start(false);
		return rootView;
	}



    @Override
    protected int getLayoutId() {
        return R.layout.fragment_scanner_list;
    }

    @Override
	public void onDestroy() {
        super.onDestroy();
		
		getActivity().unregisterReceiver(mReceiver);
    }
	
	public void PairedListUpdate(String last_addr) {
		mBTpaired = mBTadapter.getBondedDevices();
		DeviceList = new ArrayList<ClassScanner>();
		for(BluetoothDevice btd : mBTpaired) {
			int icon = (btd.getAddress().equals(last_addr)) ? R.drawable.ic_action_save : R.drawable.ic_action_bluetooth;
			//addDevice(btd, icon);
		}
		ListAdapter = new AdapterScanner(getActivity(), DeviceList);
		DeviceListView.setAdapter(ListAdapter);
		
		try {
        	if (mA100 != null) {
                if (mA100.getState() == RRUA100API.STATE_NONE) {
                	mA100.start();
                    mA100.bleConnect(new RRUA100API.BleConnectCallBack() {
                        @Override
                        public void connect(String data,final int type) {
                           // BluetoothDevice scanner = mBTadapter.getRemoteDevice(data);
                            if (type == 1) {
                                setConnectedScanner(data);
                                mLast_addr = data;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissWaitingDialog();
                                    if (type == 1) {
                                        ToastUtil.show(getActivity(), "连接成功");
                                        BleConstant.isfrist_connect = 1;
                                    } else if (type == 2)
                                        ToastUtil.show(getActivity(),"连接失败");
                                    else if (type == 3){
                                        setDisconnected(mLast_addr);
                                    }
                                }
                            });
                           // Message message= new Message();
                           // message.what = type;
                           //mHandler.handleMessage(message);
                        }
                    });
                }
            }
		} catch (Exception e) {
			Log.e("dsm362", "MainActivity - onResume: " + e.getMessage());
		}
	}


	
	private void addDevice(BluetoothDevice btd, int type) {
		if(btd.getName() == null) return;
		
		String name = btd.getName().toUpperCase();
		int index = 0;
		
		for(index = 0; index < DeviceList.size(); index++) {
			ClassScanner temp = DeviceList.get(index);
			if(temp.getName().equals(btd.getName())) break;
		}
		
		if(index != DeviceList.size()) return;
					
		if(name.startsWith(BleConstant.RFID_DEVICE_NAME)) {
			DeviceList.add(new ClassScanner(R.drawable.a100, type, btd));
		}
	}
	
	public void setBTadaper(BluetoothAdapter bta) {
		mBTadapter = bta;
	}
	
	public void setA100(RRUA100API A100) {
		if(A100 != null) mA100 = A100;
	}
	
	public void setConnectedScanner(String last_addr) {
		int index = 0;
		int selectedIndex = -1;
		
		for(index = 0; index < DeviceList.size(); index++) {
			ClassScanner temp = DeviceList.get(index);
			temp.setDisConnected(last_addr);
			if(temp.getMac().equals(last_addr)) selectedIndex = index;
		}
		
		if(index != DeviceList.size()) return;
		
		ClassScanner connected = DeviceList.get(selectedIndex);
		connected.setConnected();
		getActivity().runOnUiThread(updateListTable);
	}
	
	public void setDisconnected(String last_addr) {
		int index = 0;
		
		for(index = 0; index < DeviceList.size(); index++) {
			ClassScanner temp = DeviceList.get(index);
			temp.setDisConnected(last_addr);
		}
		getActivity().runOnUiThread(updateListTable);
	}

	
	public void pairDevice(BluetoothDevice device) {
		try {
            Method m = device.getClass().getMethod("createBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            Log.e("dsm362-pairDevice", e.getMessage());
        }


		/*
		String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
        Intent intent = new Intent(ACTION_PAIRING_REQUEST);
        String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
        intent.putExtra(EXTRA_DEVICE, device);
        String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT";
        int PAIRING_VARIANT_PIN = 1234;
        intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getActivity().startActivityForResult(intent,0);
        */
	}
	
	private void unpairDevice(BluetoothDevice device) {
		try {
			Method m = device.getClass().getMethod("removeBond", (Class[]) null);
			m.invoke(device, (Object[]) null);
		} catch (Exception e) {
			Log.e("dsm362-unpairDevice", e.getMessage());
		}
	}
	
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
	    public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

	      /*  if(LocationClient.hasError(intent)) {
	        	int errorCode = LocationClient.getErrorCode(intent);
	            Log.e("dsm362", "Location Services error: " + Integer.toString(errorCode));
	            return;
	        }*/
	        // When discovery finds a device
	        if(BluetoothDevice.ACTION_FOUND.equals(action)) {
	            // Get the BluetoothDevice object from the Intent
	            // Add the name and address to an array adapter to show in a ListView
	            addDevice(device, R.drawable.ic_action_new);
	            getActivity().runOnUiThread(updateListTable);
	        }
	        else if (ACTION_PAIRING_REQUEST.equals(action)) {
	        	setBluetoothPairingPin(device);
	        }
	        // When the device bond state changed.
			else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
				int prevBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
				int bondState = intent.getIntExtra(
                    BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
			
				if(bondState == BluetoothDevice.BOND_BONDING) {
					Log.i("dsm362", "BOND_BONDING");
					pairDevice(device);
				} else if(bondState == BluetoothDevice.BOND_BONDED) {
					Log.i("dsm362", "BOND_BONDED");
				} else if(bondState == BluetoothDevice.BOND_NONE) {
					Log.i("dsm362", "BOND_NONE");
				} else if(bondState == BluetoothDevice.ERROR) {
					Log.i("dsm362", "ERROR");
				}

				if (prevBondState == BluetoothDevice.BOND_BONDED && bondState == BluetoothDevice.BOND_NONE) {
					//BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					//pairDevice(device);
					//Log.i("dsm362", "pair start");
				} else if (prevBondState == BluetoothDevice.BOND_BONDING && bondState == BluetoothDevice.BOND_BONDED) {
					//BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					//Log.i("dsm362", "???");
				}
			} else if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
				//MainActivity main_act = (MainActivity) getActivity();
				//main_act.ScannerDisconnectedEventHandler();
			} else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				Toast.makeText(getActivity(), "BT discovery finished", Toast.LENGTH_SHORT).show();
				if(discover_dialog != null) {
					discover_dialog.cancel();
					discover_dialog = null;
				}
			}
	    }
	};
	
	public void setBluetoothPairingPin(BluetoothDevice device)
	{
		String string = "1234";
		
	    byte[] pinBytes = string.getBytes();
	    try {
	          //Log.d(TAG, "Try to set the PIN");
			Method m = device.getClass().getMethod("setPin", byte[].class);
	        m.invoke(device, pinBytes);       
	        Log.d("dsm362", "Success to add the PIN.");
	          try {
	        	  	device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
	                Log.d("dsm362", "Success to setPairingConfirmation.");
	            } catch (Exception e) {
	                // TODO Auto-generated catch block
	         //       Log.e(TAG, e.getMessage());
	                e.printStackTrace();
	            } 
	        } catch (Exception e) {
	        //  Log.e(TAG, e.getMessage());
	          e.printStackTrace();
	        }
	}
	
	private ProgressDialog discover_dialog = null;
	
	public void discovery_start(boolean isShow) {
        DeviceList.clear();
        ListAdapter.notifyDataSetChanged();
		if (mBTadapter.isDiscovering() == false) {
			mBTadapter.startDiscovery();
			if (isShow) {
                discover_dialog = new ProgressDialog(getActivity());
                discover_dialog.setMessage("Finding Scanner...");
                discover_dialog.setButton(Dialog.BUTTON_NEGATIVE, "Stop", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mBTadapter.isDiscovering()) mBTadapter.cancelDiscovery();
                    }
                });
                discover_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
                discover_dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (mBTadapter.isDiscovering()) mBTadapter.cancelDiscovery();
                    }
                });
                discover_dialog.show();
            }
		}
	}
	
	public Runnable updateListTable = new Runnable() {
		public void run() {
			FragmentScannerListFragment.this.ListAdapter.notifyDataSetChanged();
		}
	};
	
	@Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_BT_search) {
			//Toast.makeText(getActivity(), "OneFragment", Toast.LENGTH_SHORT).show();
        	if (mBTadapter.isDiscovering() == false) discovery_start(true);
		}
    }
	
	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        	if(mA100 == null) return;
        	
        	final ClassScanner target = DeviceList.get(position);
        	if(target.getConnected()) {
        		mA100.stop();
        	} else {
        		if(mA100.isConnected() == true) mA100.stop();
        		mA100.connect(target.getDevice());
        		showWaitingDialog("请等待",false);
        	}
        }
    };
    
    private OnItemLongClickListener mDeviceLongClickListener = new OnItemLongClickListener() {
    	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
        {
    		final int index = position;
    		final ClassScanner target = DeviceList.get(index);

    		AlertDialog.Builder alertDlg = new AlertDialog.Builder(view.getContext());
            alertDlg.setTitle("Scanner Remove");
            alertDlg.setMessage(String.format("Do you want to remove %s in list? ", target.getName()));

            alertDlg.setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                 @Override
                 public void onClick(DialogInterface dialog, int which)
                 {
                	 if(target.getType() == R.drawable.ic_action_bluetooth_connected) {
                		 mA100.stop();
                	 }
                	 unpairDevice(target.getDevice());
                	 DeviceList.remove(index);
                	 getActivity().runOnUiThread(updateListTable);
                	 
                	 MainActivity main_act = (MainActivity) getActivity();
	                 Editor editor = main_act.mPref.edit();
	                 editor.remove(main_act.KEY_LAST_ADDR_STRING);
	                 editor.putString(main_act.KEY_LAST_ADDR_STRING, null);
	                 editor.commit();
	                 
                     dialog.dismiss();  // AlertDialog�� �ݴ´�.
                 }
            });
            
            alertDlg.setNegativeButton("No" , new DialogInterface.OnClickListener()
            {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                     dialog.dismiss();  // AlertDialog�� �ݴ´�.
                 }
            });
            alertDlg.show();
    		
            return true;
        }
    };

	public void ConnectTo(BluetoothDevice scanner) {
		// TODO Auto-generated method stub
		if(mA100 != null) {
    		if(mA100.isConnected() == true) {
    			mA100.stop();
    		}
    		mA100.connect(scanner);
    	}
	}
}
